package http

import (
	bytes2 "bytes"
	"fmt"
	"io"
	"log-record/store"
	"net/http"
	"net/url"
	"time"
)

func queryRemoteAllApp(res http.ResponseWriter, req *http.Request) {
	log := store.RemoteLog{}
	writeJson(SuccessData(log.QueryAllApplication()), &res)
}

func queryRemoteAllLevel(res http.ResponseWriter, req *http.Request) {
	parse, err := url.Parse(req.RequestURI)
	if err != nil {
		writeJson(ErrorMessage(err.Error()), &res)
		return
	}
	log := store.RemoteLog{}
	writeJson(SuccessData(log.QueryAllLevel(parse.Query())), &res)
}

func queryRemoteAllIp(res http.ResponseWriter, req *http.Request) {
	parse, err := url.Parse(req.RequestURI)
	if err != nil {
		writeJson(ErrorMessage(err.Error()), &res)
		return
	}
	log := store.RemoteLog{}
	writeJson(SuccessData(log.QueryAllIp(parse.Query())), &res)
}

func queryRemoteLogs(res http.ResponseWriter, req *http.Request) {
	parse, err := url.Parse(req.RequestURI)
	if err != nil {
		writeJson(ErrorMessage(err.Error()), &res)
		return
	}
	log := store.RemoteLog{}
	logs, count := log.QueryLogs(parse.Query())
	buffer := bytes2.NewBufferString("")
	for _, log := range logs {
		message := fmt.Sprintf(`<span style='font-size: 12px'>%v [%v]|-<span style='color: #358b99'>%v</span> <span style='color: green'>%v</span>-<span style='color: red'>%v</span></span><br/><br/>`,
			time.UnixMilli(log.Timestamp).Format("2006-01-02 15:04:05"),
			log.Thread,
			log.Level,
			log.LoggerName,
			log.Message)
		buffer.Write([]byte(message))
	}
	res.Header().Set("total", fmt.Sprintf("%v", count))
	res.Header().Set("Content-Type", "text/html;charset=UTF-8")
	bytes, err := io.ReadAll(buffer)
	if err != nil {
		fmt.Println(err)
		return
	}
	_, _ = res.Write(bytes)
}
